package com.wen.rabbitmq.routing;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

//routing模式，根据key去选择消息发布的队列
public class Producer {

    public static void main(String[] args) {
        //1.创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("120.26.47.111");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("admin");
        //虚拟访问节点
        connectionFactory.setVirtualHost("/");
        //2.创建连接connection
        Connection connection =null;
        Channel channel = null;
        try{
            connection = connectionFactory.newConnection("生产者");
            //3.通过连接获取通道channel
            channel = connection.createChannel();
            //4.创建交换机、声明队列、绑定关系、路由key、发送消息
//            String queueName = "queue1";
            String exchange = "direct-exchange";
            String routingKey = "sms";
            String type = "direct";
            /**
             * param1 队列的名称
             * param2 是否要持久化
             * param3 排他性，是否是独占独立
             * param4 是否自动删除，随着随着最后一个消费者消费完毕以后是否把队列删除
             * param5 携带附属参数
             */
//            channel.queueDeclare(queueName,true,false,false,null);
            //5.准备发送内容
            String message = "Hello RabbitMQ";
            //6.发送消息给队列
            //param1 交换价  param2 队列、路由key  param3 消息的控制状态  param4 消息主体
            //虽然没有指定交换机，但是一定会有一个默认的交换机
            channel.basicPublish(exchange,routingKey,null,message.getBytes());
            System.err.println("消息发送成功");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //7.关闭通道
            if(channel!=null && channel.isOpen()){
                try {
                    channel.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            //8.关闭连接
            if(connection!=null && connection.isOpen()){
                try {
                    connection.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }
}
